package com.tanhua.management.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.LogManagementApi;
import com.tanhua.dubbo.server.api.MyCenterApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserPageInfoApi;
import com.tanhua.dubbo.server.pojo.LogRecord;
import com.tanhua.management.vo.LogManagerVo;
import com.tanhua.management.vo.PageResult;
import com.tanhua.management.vo.UserBaseInfoVo;
import com.tanhua.management.vo.UserPageInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class UserPageInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Reference(version = "1.0.0")
    private UserPageInfoApi userPageInfoApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private MyCenterApi myCenterApi;

    @Reference(version = "1.0.0")
    private LogManagementApi logManagementApi;

    /**
     * 用户数据翻页
     *
     * @param page
     * @param pagesize
     * @param id             //搜索条件
     * @param nickname//搜索条件
     * @param city//搜索条件
     * @return
     */
    public PageResult queryUserPageInfo(int page, int pagesize, String id, String nickname, String city) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(id)) {
            wrapper.like("user_id", id);
        }
        if (ObjectUtil.isNotEmpty(nickname)) {
            wrapper.like("nick_name", nickname);
        }
        if (ObjectUtil.isNotEmpty(city)) {
            wrapper.like("city", city);
        }
        Page<UserInfo> pager = new Page<>(page, pagesize);
        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(pager, wrapper);

        List<UserInfo> userInfoList = userInfoIPage.getRecords();
        List<Object> userIds = CollUtil.getFieldValues(userInfoList, "userId");
        List<Long> userList = new ArrayList<>();
        for (Object userId : userIds) {
            userList.add(Convert.toLong(userId));
        }
        List<User> users = userMapper.selectBatchIds(userList);
        List<UserPageInfoVo> userPageInfoVoList = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            UserPageInfoVo userPageInfoVo = new UserPageInfoVo();

            BeanUtil.copyProperties(userInfo, userPageInfoVo);
            userPageInfoVo.setId(Convert.toInt(userInfo.getUserId()));
            userPageInfoVo.setSex(SexEnum.getSexByValue(userInfo.getSex().getValue()));
            userPageInfoVo.setUserStatus(userPageInfoApi.queryUserIsFreeze(userPageInfoVo.getId()) ? "2" : "1");
            userPageInfoVo.setLogoStatus("1");//头像审核状态,前端功能未作,写死的数据

            List<LogRecord> logRecordList = logManagementApi.queryUserListRecentActivity(userList);
            for (LogRecord logRecord : logRecordList) {
                if (userPageInfoVo.getId() == Convert.toInt(logRecord.getUserId())) {
                    userPageInfoVo.setLastActiveTime(logRecord.getLogTime());//最近活跃时间
                    break;
                }
            }

            for (User user : users) {
                if (userInfo.getUserId() == user.getId()) {
                    userPageInfoVo.setMobile(user.getMobile());
                }
            }

            userPageInfoVoList.add(userPageInfoVo);
        }
        pageResult.setCounts(Convert.toInt(userInfoIPage.getTotal()));
        pageResult.setPages(Convert.toInt(userInfoIPage.getPages()));
        pageResult.setItems(userPageInfoVoList);
        return pageResult;
    }

    /**
     * 根据单个id查询用户基本资料
     *
     * @param userID
     * @return
     */
    public UserBaseInfoVo queryUserBaseInfo(Integer userID) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userID);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        User user = userMapper.selectById(userID);
        UserBaseInfoVo userBaseInfoVo = new UserBaseInfoVo();
        BeanUtil.copyProperties(userInfo, userBaseInfoVo,"income");
        userBaseInfoVo.setIncome(Convert.toInt(userInfo.getIncome())*1000);
        userBaseInfoVo.setMobile(user.getMobile());
        userBaseInfoVo.setCreated(userInfo.getCreated().getTime());
        String personalSignature = userInfo.getPersonalSignature();
        if (ObjectUtil.isEmpty(personalSignature)) {
            personalSignature = "人多时，管住嘴。人少时，管住心。";
        }
        userBaseInfoVo.setPersonalSignature(personalSignature);
        userBaseInfoVo.setCountBeLiked(myCenterApi.queryFanCount(Convert.toLong(userID)));
        userBaseInfoVo.setCountLiked(myCenterApi.queryLoveCount(Convert.toLong(userID)));
        userBaseInfoVo.setCountMatching(myCenterApi.queryEachLoveCount(Convert.toLong(userID)));
        userBaseInfoVo.setUserStatus(userPageInfoApi.queryUserIsFreeze(userID) ? "2" : "1");
        userBaseInfoVo.setLastActiveTime(logManagementApi.queryUserRecentActivity(userID).getLogTime());//最近活跃时间
        userBaseInfoVo.setLastLoginLocation(logManagementApi.queryUserRecentActivity(userID).getLogAddress());//最近登录地

        return userBaseInfoVo;
    }

    /**
     * 冻结用户
     *
     * @return
     */
    public String freezeUser(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        return userPageInfoApi.freezeUser(userId, freezingTime, freezingRange, reasonsForFreezing, frozenRemarks);
    }

    /**
     * 用户解冻操作
     *
     * @param userId
     * @param reasonsForThawing
     * @return
     */
    public String unfreezeUser(Integer userId, String reasonsForThawing) {
        return userPageInfoApi.unfreezeUser(userId, reasonsForThawing);
    }
}
